package com.bishe.app.core.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 其中image表示访问的前缀。"file:F:/img/"是文件真实的存储路径
        registry.addResourceHandler("/**")
                .addResourceLocations("file://" + System.getProperty("user.dir") + "/images/");
    }

    //解决跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET" , "POST" , "DELETE" , "PUT" , "PATCH" , "OPTIONS")
                .maxAge(3600);
    }

    @Bean
    SessionInterceptor getSessionInterceptor() {
        return new SessionInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> whiteList = new ArrayList<>();

        // 从配置文件 resources/whitelist.txt
        InputStream inputStream = this.getClass().getResourceAsStream("/whitelist.txt");
        if (inputStream == null) {
            log.warn("Failed to read whitelist.txt!");
        } else {
            List<String> lines = new ArrayList<>();
            IoUtil.readUtf8Lines(inputStream, lines);
            for (String path : lines) {
                if (!StrUtil.isEmpty(path)) {
                    log.info("exclude path: {}", path);
                    whiteList.add(path);
                }
            }
        }
        registry.addInterceptor(getSessionInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(whiteList);
    }

}
